import Vue from 'vue'
import axios from "axios"
import config from "../../config"
import {Message, Notification} from 'element-ui'
import store from "../store.js"

/**
 * @param method eg: get|post|put|delete|GET|POST|PUT|DELETE
 * @param path eg: /user/list
 * @param data 请求携带的body参数，json请求方式，传对象
 * @param testData function|object  测试模式时返回的数据,工厂函数或者具体数据
 * @param success function 成功的回调函数
 * @param fail function
 * @param complete function
 * @param showLoading 是否需要遮罩, 默认有
 * @return Promise<object>
 */
export default function ({method = "GET", path, data, testData, success, fail, complete, showLoading}) {
    if (config.useTest) { // 是否是测试模式
        Notification.info({
            message: "[测试成功] apiPath=" + path,
            duration: 500,
        })
        if (typeof (testData) == "function")
            testData = testData()
        console.log(`[测试成功] [${method}] apiPath=${path} testData: `, testData)
        if (success) success({
            code: 20000,
            msg: "mock:ok",
            data: testData
        })
        return
    }

    let loading = null
    if (showLoading == null || showLoading === true) {
        loading = Vue.prototype.$loading({ // 加载中遮罩层
            lock: true,
            background: "rgba(0,0,0,0.05)",
            text: "加载中...",
        })
    }
    axios.request({
        method: method,
        baseURL: config.baseUrl,
        url: path,
        data: data, // 参数，object, 会自动转换成json字符串
        headers: {
            "token": window.localStorage.getItem("token")
        },
        timeout: 5000,
    }).then(response => { // status在[200,400)之间
        if (response.headers && (response.headers.token || response.headers.Token)) {
            console.log("更新token")
            window.localStorage.setItem("token", response.header.token ? response.headers.token : response.headers.Token)
        }
        console.log(`[${method}] ${path} response: `, response)
        let res = response.data
        if (res.code >= 0 && res.code < 30000) {
            if (success) success(res)
        } else if (40100 <= res.code && res.code < 40200) {
            window.localStorage.removeItem('token')
            store.commit("setUserInfo", {})
            Message.error('未登录或登录已经过期，请重新登录')
        } else {
            if (fail) fail(res)
            else Message.error("业务异常: " + res.msg)
        }
    }).catch(err => { // 404,500，服务器断网等
        Notification.error("服务异常: " + err)
    }).finally(() => {
        if (complete) complete()
        if (loading)
            loading.close()
    })
}

